package room

import (
	"gitee.com/game_diamond/consts"
	"gitee.com/game_diamond/protocols"
	"gitee.com/game_diamond/server"
	"gitee.com/game_diamond/session"
	"qiniupkg.com/x/errors.v7"
)

type Message struct {
	UserId int
	Actor  int
	Body   *protocols.WebSocketBody
}

type UserSession struct {
	UserId  int
	Actor   int
	Session interface{}
}

type Room struct {
	RoomId       string
	RoomType     int //房间类型：0正课；1补课
	OwnerId      int
	ClassId      int
	CourseId     int
	DelayTask    []int
	LoopTask     []int
	StudentCount int
	BitCount     int //标志位，只增，用于计算登录学生的顺序
	CreateTime   int
	Sessions     map[int]*UserSession
}

func (r *Room) Init() {
	r.Sessions = make(map[int]*UserSession)
}

//session
func (r *Room) SessionExist(userId int) bool {
	if r.Sessions == nil {
		return false
	}
	if _, ok := r.Sessions[userId]; ok {
		return true
	}
	return false
}

func (r *Room) AddSession(us *UserSession) error {
	r.Sessions[us.UserId] = us
	return nil
}

func (r *Room) GetSession(userId int) (*UserSession, error) {
	if !r.SessionExist(userId) {
		return nil, errorSessionNotExist
	}
	if r.Sessions[userId] == nil {
		return nil, errorSessionNotExist
	}
	return r.Sessions[userId], nil
}

//userIds
func (r *Room) GetAllUserIds() []int {
	ids := make([]int, 0)
	for _, o := range r.Sessions {
		if o.Session == nil {
			continue
		}
		ids = append(ids, o.UserId)
	}
	return ids
}

func (r *Room) GetAllStudentIds() []int {
	ids := make([]int, 0)
	for _, o := range r.Sessions {
		if o.Actor != consts.ActorStudent || o.Session == nil {
			continue
		}
		ids = append(ids, o.UserId)
	}
	return ids
}

func (r *Room) GetTeacherId() int {
	return r.OwnerId
}

//action

func (r *Room) Enter(studentId int) error {
	r.StudentCount++
	//roomOrder
	r.BitCount++
	gl := session.GetGlobalStudentSession(studentId)
	gl.RoomOrder = r.BitCount
	gl.Save()
	return nil
}

func (r *Room) Leave(studentId int) error {
	r.StudentCount--
	return nil
}

func (r *Room) GC() {
	//**log begin gc
	//student gc
	//teacher gc
	//delete roomList

	//**log gc success
}
